import { PNG } from "pngjs";
import * as fs from "node:fs"
import { Image, Pixel } from "./hp3-img.js";

export function savePng(width:number, height:number, pixels:Pixel[], file:string){
    const png = new PNG({
        width: width,
        height: height
    });
    for(let y=0; y<height; y++){
        for(let x=0; x<width; x++){
            const index = y*width+x;
            if(index<pixels.length){
                const base = index*4;
                const p = pixels[index];
                png.data[base] = p.r;
                png.data[base+1] = p.g;
                png.data[base+2] = p.b;
                png.data[base+3] = p.a;
            }
        }
    }
    const buffer = PNG.sync.write(png);
    fs.writeFileSync(file,buffer);
}

export function loadPng(file:string):Image{
    const buffer = fs.readFileSync(file);
    const png = PNG.sync.read(buffer);
    const rst:Image = {
        width: png.width,
        height: png.height,
        pixels: []
    }
    for(let y=0; y<png.height; y++){
        for(let x=0; x<png.width; x++){
            const index = y*png.width+x;
            const base = index*4;
            if(base+3<png.data.length){
                const r = png.data[base];
                const g = png.data[base+1];
                const b = png.data[base+2];
                const a = png.data[base+3];
                rst.pixels.push({
                    r: r,
                    g: g,
                    b: b,
                    a: a
                });
            }
        }
    }
    return rst;
}
